require 'digest/sha1'
	
class Account < ActiveRecord::Base
	belongs_to :employee
	belongs_to :role

  # Please change the salt to something else, 
  # Every application should use a different one 
  @@salt = 'change-me'
  cattr_accessor :salt

  # Authenticate a user. 
  #
  # Example:
  #   @account = Account.authenticate('bob', 'bobpass')
  #
  def self.authenticate(login, pass)
    account = find_first(["id = ? AND password = ?", login, sha1(pass)])
    if (account and account.employee.state == 1)
    	return account
    else
    	return nil
    end
  end  
  
  # Return true/false if User is authorized for resource.
  def authorized?(resource)
    return permission_strings.include?(resource)
  end

  # Load permission strings 
  def permission_strings
    a = []
    self.role.rights.each{|r| a<< r.url }
    a
  end
  
  protected

  # Apply SHA1 encryption to the supplied password. 
  # We will additionally surround the password with a salt 
  # for additional security. 
  def self.sha1(pass)
    Digest::SHA1.hexdigest("#{salt}--#{pass}--")
  end
    
  before_create :crypt_password
  
  # Before saving the record to database we will crypt the password 
  # using SHA1. 
  # We never store the actual password in the DB.
  def crypt_password
    write_attribute "password", self.class.sha1(password)
  end
  
  before_update :crypt_unless_empty
  
  # If the record is updated we will check if the password is empty.
  # If its empty we assume that the user didn't want to change his
  # password and just reset it to the old value.
  def crypt_unless_empty
    account = self.class.find(self.id)
    if password.empty?      
      self.password = account.password
    elsif self.password != account.password
      write_attribute "password", self.class.sha1(password)
    end        
  end
  
  #validates_uniqueness_of :login, :on => :create

  #validates_confirmation_of :password,:message=>"密码不匹配"
  #validates_length_of :login, :within => 3..10,:message=>"长度必需为3到40个字节"
  #validates_length_of :password, :within => 5..10,:message=>"长度必需为5到40个字节"
  validates_presence_of :password, :message=>"该字段不可为空"

end
